
from selenium.webdriver.common.by import By


def parse_locator_str(locator_str):
    """尝试返回locator字符串类型，如果没匹配到，则返回None，仿照selenium Library的写法
    """
    if locator_str.startswith(('//', '(//')):
        return By.XPATH, locator_str

    SELECTOR_TYPES = {
        'id': By.ID,
        'name': By.NAME,
        'xpath': By.XPATH,
        'link': By.LINK_TEXT,
        'partial link': By.PARTIAL_LINK_TEXT,
        'css': By.CSS_SELECTOR,
        'class': By.CLASS_NAME,
        'tag': By.TAG_NAME,
    }
    if '=' not in locator_str:
        index = locator_str.find(':')
    elif ':' not in locator_str:
        index = locator_str.find('=')
    else:
        index = min(locator_str.find('='), locator_str.find(':'))

    if index != -1:
        prefix = locator_str[:index].strip()
        if prefix in SELECTOR_TYPES:
            return SELECTOR_TYPES[prefix], locator_str[index + 1:].lstrip()
    return None, locator_str
